blob: d63cd0e82f66567b81b9db1f62aef3da6f8da2cc [file] [log] [blame]
Bill Wendling0f940c92007-12-07 21:42:31 +00001//===-- MachineLICM.cpp - Machine Loop Invariant Code Motion Pass ---------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Bill Wendling0f940c92007-12-07 21:42:31 +00007//
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//
Dan Gohmanc475c362009-01-15 22:01:38 +000013// 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//
Bill Wendling0f940c92007-12-07 21:42:31 +000021//===----------------------------------------------------------------------===//
22
23#define DEBUG_TYPE "machine-licm"
Chris Lattnerac695822008-01-04 06:41:45 +000024#include "llvm/CodeGen/Passes.h"
Bill Wendling0f940c92007-12-07 21:42:31 +000025#include "llvm/CodeGen/MachineDominators.h"
Bill Wendling0f940c92007-12-07 21:42:31 +000026#include "llvm/CodeGen/MachineLoopInfo.h"
Dan Gohman589f1f52009-10-28 03:21:57 +000027#include "llvm/CodeGen/MachineMemOperand.h"
Bill Wendling9258cd32008-01-02 19:32:43 +000028#include "llvm/CodeGen/MachineRegisterInfo.h"
Dan Gohman589f1f52009-10-28 03:21:57 +000029#include "llvm/CodeGen/PseudoSourceValue.h"
Dan Gohman6f0d0242008-02-10 18:45:23 +000030#include "llvm/Target/TargetRegisterInfo.h"
Bill Wendlingefe2be72007-12-11 23:27:51 +000031#include "llvm/Target/TargetInstrInfo.h"
Bill Wendling0f940c92007-12-07 21:42:31 +000032#include "llvm/Target/TargetMachine.h"
Dan Gohmane33f44c2009-10-07 17:38:06 +000033#include "llvm/Analysis/AliasAnalysis.h"
Evan Chengaf6949d2009-02-05 08:45:46 +000034#include "llvm/ADT/DenseMap.h"
Chris Lattnerac695822008-01-04 06:41:45 +000035#include "llvm/ADT/Statistic.h"
Chris Lattnerac695822008-01-04 06:41:45 +000036#include "llvm/Support/Debug.h"
Daniel Dunbarce63ffb2009-07-25 00:23:56 +000037#include "llvm/Support/raw_ostream.h"
Bill Wendling0f940c92007-12-07 21:42:31 +000038
39using namespace llvm;
40
Bill Wendling041b3f82007-12-08 23:58:46 +000041STATISTIC(NumHoisted, "Number of machine instructions hoisted out of loops");
Evan Chengaf6949d2009-02-05 08:45:46 +000042STATISTIC(NumCSEed, "Number of hoisted machine instructions CSEed");
Bill Wendlingb48519c2007-12-08 01:47:01 +000043
Bill Wendling0f940c92007-12-07 21:42:31 +000044namespace {
Nick Lewycky6726b6d2009-10-25 06:33:48 +000045 class MachineLICM : public MachineFunctionPass {
Bill Wendling9258cd32008-01-02 19:32:43 +000046 const TargetMachine *TM;
Bill Wendlingefe2be72007-12-11 23:27:51 +000047 const TargetInstrInfo *TII;
Dan Gohmana8fb3362009-09-25 23:58:45 +000048 const TargetRegisterInfo *TRI;
Dan Gohman45094e32009-09-26 02:34:00 +000049 BitVector AllocatableSet;
Bill Wendling12ebf142007-12-11 19:40:06 +000050
Bill Wendling0f940c92007-12-07 21:42:31 +000051 // Various analyses that we use...
Dan Gohmane33f44c2009-10-07 17:38:06 +000052 AliasAnalysis *AA; // Alias analysis info.
Bill Wendlinge4fc1cc2008-05-12 19:38:32 +000053 MachineLoopInfo *LI; // Current MachineLoopInfo
54 MachineDominatorTree *DT; // Machine dominator tree for the cur loop
Bill Wendling9258cd32008-01-02 19:32:43 +000055 MachineRegisterInfo *RegInfo; // Machine register information
Bill Wendling0f940c92007-12-07 21:42:31 +000056
Bill Wendling0f940c92007-12-07 21:42:31 +000057 // State that is updated as we process loops
Bill Wendlinge4fc1cc2008-05-12 19:38:32 +000058 bool Changed; // True if a loop is changed.
59 MachineLoop *CurLoop; // The current loop we are working on.
Dan Gohmanc475c362009-01-15 22:01:38 +000060 MachineBasicBlock *CurPreheader; // The preheader for CurLoop.
Evan Chengaf6949d2009-02-05 08:45:46 +000061
62 // For each BB and opcode pair, keep a list of hoisted instructions.
63 DenseMap<std::pair<unsigned, unsigned>,
64 std::vector<const MachineInstr*> > CSEMap;
Bill Wendling0f940c92007-12-07 21:42:31 +000065 public:
66 static char ID; // Pass identification, replacement for typeid
Dan Gohmanae73dc12008-09-04 17:05:41 +000067 MachineLICM() : MachineFunctionPass(&ID) {}
Bill Wendling0f940c92007-12-07 21:42:31 +000068
69 virtual bool runOnMachineFunction(MachineFunction &MF);
70
Dan Gohman72241702008-12-18 01:37:56 +000071 const char *getPassName() const { return "Machine Instruction LICM"; }
72
Bill Wendling074223a2008-03-10 08:13:01 +000073 // FIXME: Loop preheaders?
Bill Wendling0f940c92007-12-07 21:42:31 +000074 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
75 AU.setPreservesCFG();
76 AU.addRequired<MachineLoopInfo>();
77 AU.addRequired<MachineDominatorTree>();
Dan Gohmane33f44c2009-10-07 17:38:06 +000078 AU.addRequired<AliasAnalysis>();
Bill Wendlingd5da7042008-01-04 08:48:49 +000079 AU.addPreserved<MachineLoopInfo>();
80 AU.addPreserved<MachineDominatorTree>();
81 MachineFunctionPass::getAnalysisUsage(AU);
Bill Wendling0f940c92007-12-07 21:42:31 +000082 }
Evan Chengaf6949d2009-02-05 08:45:46 +000083
84 virtual void releaseMemory() {
85 CSEMap.clear();
86 }
87
Bill Wendling0f940c92007-12-07 21:42:31 +000088 private:
Bill Wendling041b3f82007-12-08 23:58:46 +000089 /// IsLoopInvariantInst - Returns true if the instruction is loop
Bill Wendling0f940c92007-12-07 21:42:31 +000090 /// invariant. I.e., all virtual register operands are defined outside of
91 /// the loop, physical registers aren't accessed (explicitly or implicitly),
92 /// and the instruction is hoistable.
93 ///
Bill Wendling041b3f82007-12-08 23:58:46 +000094 bool IsLoopInvariantInst(MachineInstr &I);
Bill Wendling0f940c92007-12-07 21:42:31 +000095
Evan Cheng45e94d62009-02-04 09:19:56 +000096 /// IsProfitableToHoist - Return true if it is potentially profitable to
97 /// hoist the given loop invariant.
98 bool IsProfitableToHoist(MachineInstr &MI);
99
Bill Wendling0f940c92007-12-07 21:42:31 +0000100 /// HoistRegion - Walk the specified region of the CFG (defined by all
101 /// blocks dominated by the specified block, and that are in the current
102 /// loop) in depth first order w.r.t the DominatorTree. This allows us to
103 /// visit definitions before uses, allowing us to hoist a loop body in one
104 /// pass without iteration.
105 ///
106 void HoistRegion(MachineDomTreeNode *N);
107
108 /// Hoist - When an instruction is found to only use loop invariant operands
109 /// that is safe to hoist, this instruction is called to do the dirty work.
110 ///
Dan Gohman589f1f52009-10-28 03:21:57 +0000111 void Hoist(MachineInstr *MI);
Bill Wendling0f940c92007-12-07 21:42:31 +0000112 };
Bill Wendling0f940c92007-12-07 21:42:31 +0000113} // end anonymous namespace
114
Dan Gohman844731a2008-05-13 00:00:25 +0000115char MachineLICM::ID = 0;
116static RegisterPass<MachineLICM>
Bill Wendling8870ce92008-07-07 05:42:27 +0000117X("machinelicm", "Machine Loop Invariant Code Motion");
Dan Gohman844731a2008-05-13 00:00:25 +0000118
Bill Wendling0f940c92007-12-07 21:42:31 +0000119FunctionPass *llvm::createMachineLICMPass() { return new MachineLICM(); }
120
Dan Gohmanc475c362009-01-15 22:01:38 +0000121/// LoopIsOuterMostWithPreheader - Test if the given loop is the outer-most
122/// loop that has a preheader.
123static bool LoopIsOuterMostWithPreheader(MachineLoop *CurLoop) {
124 for (MachineLoop *L = CurLoop->getParentLoop(); L; L = L->getParentLoop())
125 if (L->getLoopPreheader())
126 return false;
127 return true;
128}
129
Bill Wendling0f940c92007-12-07 21:42:31 +0000130/// Hoist expressions out of the specified loop. Note, alias info for inner loop
131/// is not preserved so it is not a good idea to run LICM multiple times on one
132/// loop.
133///
134bool MachineLICM::runOnMachineFunction(MachineFunction &MF) {
Bill Wendlingb7a89922009-08-22 20:25:44 +0000135 DEBUG(errs() << "******** Machine LICM ********\n");
Bill Wendlinga17ad592007-12-11 22:22:22 +0000136
Bill Wendling0f940c92007-12-07 21:42:31 +0000137 Changed = false;
Bill Wendlingacb04ec2008-08-31 02:30:23 +0000138 TM = &MF.getTarget();
Bill Wendling9258cd32008-01-02 19:32:43 +0000139 TII = TM->getInstrInfo();
Dan Gohmana8fb3362009-09-25 23:58:45 +0000140 TRI = TM->getRegisterInfo();
Bill Wendlingacb04ec2008-08-31 02:30:23 +0000141 RegInfo = &MF.getRegInfo();
Dan Gohman45094e32009-09-26 02:34:00 +0000142 AllocatableSet = TRI->getAllocatableSet(MF);
Bill Wendling0f940c92007-12-07 21:42:31 +0000143
144 // Get our Loop information...
145 LI = &getAnalysis<MachineLoopInfo>();
146 DT = &getAnalysis<MachineDominatorTree>();
Dan Gohmane33f44c2009-10-07 17:38:06 +0000147 AA = &getAnalysis<AliasAnalysis>();
Bill Wendling0f940c92007-12-07 21:42:31 +0000148
149 for (MachineLoopInfo::iterator
150 I = LI->begin(), E = LI->end(); I != E; ++I) {
Bill Wendlinga17ad592007-12-11 22:22:22 +0000151 CurLoop = *I;
Bill Wendling0f940c92007-12-07 21:42:31 +0000152
Dan Gohmanc475c362009-01-15 22:01:38 +0000153 // Only visit outer-most preheader-sporting loops.
154 if (!LoopIsOuterMostWithPreheader(CurLoop))
155 continue;
156
157 // Determine the block to which to hoist instructions. If we can't find a
158 // suitable loop preheader, we can't do any hoisting.
159 //
160 // FIXME: We are only hoisting if the basic block coming into this loop
161 // has only one successor. This isn't the case in general because we haven't
162 // broken critical edges or added preheaders.
163 CurPreheader = CurLoop->getLoopPreheader();
164 if (!CurPreheader)
165 continue;
166
167 HoistRegion(DT->getNode(CurLoop->getHeader()));
Bill Wendling0f940c92007-12-07 21:42:31 +0000168 }
169
170 return Changed;
171}
172
Bill Wendling0f940c92007-12-07 21:42:31 +0000173/// HoistRegion - Walk the specified region of the CFG (defined by all blocks
174/// dominated by the specified block, and that are in the current loop) in depth
175/// first order w.r.t the DominatorTree. This allows us to visit definitions
176/// before uses, allowing us to hoist a loop body in one pass without iteration.
177///
178void MachineLICM::HoistRegion(MachineDomTreeNode *N) {
179 assert(N != 0 && "Null dominator tree node?");
180 MachineBasicBlock *BB = N->getBlock();
181
182 // If this subregion is not in the top level loop at all, exit.
183 if (!CurLoop->contains(BB)) return;
184
Dan Gohmanc475c362009-01-15 22:01:38 +0000185 for (MachineBasicBlock::iterator
Evan Chengaf6949d2009-02-05 08:45:46 +0000186 MII = BB->begin(), E = BB->end(); MII != E; ) {
187 MachineBasicBlock::iterator NextMII = MII; ++NextMII;
188 MachineInstr &MI = *MII;
Bill Wendling0f940c92007-12-07 21:42:31 +0000189
Dan Gohman589f1f52009-10-28 03:21:57 +0000190 Hoist(&MI);
Evan Chengaf6949d2009-02-05 08:45:46 +0000191
192 MII = NextMII;
Dan Gohmanc475c362009-01-15 22:01:38 +0000193 }
Bill Wendling0f940c92007-12-07 21:42:31 +0000194
195 const std::vector<MachineDomTreeNode*> &Children = N->getChildren();
196
197 for (unsigned I = 0, E = Children.size(); I != E; ++I)
198 HoistRegion(Children[I]);
199}
200
Bill Wendling041b3f82007-12-08 23:58:46 +0000201/// IsLoopInvariantInst - Returns true if the instruction is loop
Bill Wendling0f940c92007-12-07 21:42:31 +0000202/// invariant. I.e., all virtual register operands are defined outside of the
Bill Wendling60ff1a32007-12-20 01:08:10 +0000203/// loop, physical registers aren't accessed explicitly, and there are no side
204/// effects that aren't captured by the operands or other flags.
Bill Wendling0f940c92007-12-07 21:42:31 +0000205///
Bill Wendling041b3f82007-12-08 23:58:46 +0000206bool MachineLICM::IsLoopInvariantInst(MachineInstr &I) {
Chris Lattnera22edc82008-01-10 23:08:24 +0000207 const TargetInstrDesc &TID = I.getDesc();
208
209 // Ignore stuff that we obviously can't hoist.
Dan Gohman237dee12008-12-23 17:28:50 +0000210 if (TID.mayStore() || TID.isCall() || TID.isTerminator() ||
Chris Lattnera22edc82008-01-10 23:08:24 +0000211 TID.hasUnmodeledSideEffects())
212 return false;
Evan Cheng9b61f332009-02-04 07:17:49 +0000213
Chris Lattnera22edc82008-01-10 23:08:24 +0000214 if (TID.mayLoad()) {
Bill Wendlinge4fc1cc2008-05-12 19:38:32 +0000215 // Okay, this instruction does a load. As a refinement, we allow the target
216 // to decide whether the loaded value is actually a constant. If so, we can
217 // actually use it as a load.
Dan Gohmane33f44c2009-10-07 17:38:06 +0000218 if (!I.isInvariantLoad(AA))
Chris Lattnera22edc82008-01-10 23:08:24 +0000219 // FIXME: we should be able to sink loads with no other side effects if
220 // there is nothing that can change memory from here until the end of
Bill Wendlinge4fc1cc2008-05-12 19:38:32 +0000221 // block. This is a trivial form of alias analysis.
Chris Lattnera22edc82008-01-10 23:08:24 +0000222 return false;
Chris Lattnera22edc82008-01-10 23:08:24 +0000223 }
Bill Wendling074223a2008-03-10 08:13:01 +0000224
Bill Wendling280f4562007-12-18 21:38:04 +0000225 DEBUG({
Bill Wendlingb7a89922009-08-22 20:25:44 +0000226 errs() << "--- Checking if we can hoist " << I;
Chris Lattner749c6f62008-01-07 07:27:27 +0000227 if (I.getDesc().getImplicitUses()) {
Bill Wendlingb7a89922009-08-22 20:25:44 +0000228 errs() << " * Instruction has implicit uses:\n";
Bill Wendling280f4562007-12-18 21:38:04 +0000229
Dan Gohman6f0d0242008-02-10 18:45:23 +0000230 const TargetRegisterInfo *TRI = TM->getRegisterInfo();
Chris Lattner749c6f62008-01-07 07:27:27 +0000231 for (const unsigned *ImpUses = I.getDesc().getImplicitUses();
Chris Lattner69244302008-01-07 01:56:04 +0000232 *ImpUses; ++ImpUses)
Bill Wendlingb7a89922009-08-22 20:25:44 +0000233 errs() << " -> " << TRI->getName(*ImpUses) << "\n";
Bill Wendling280f4562007-12-18 21:38:04 +0000234 }
235
Chris Lattner749c6f62008-01-07 07:27:27 +0000236 if (I.getDesc().getImplicitDefs()) {
Bill Wendlingb7a89922009-08-22 20:25:44 +0000237 errs() << " * Instruction has implicit defines:\n";
Bill Wendling280f4562007-12-18 21:38:04 +0000238
Dan Gohman6f0d0242008-02-10 18:45:23 +0000239 const TargetRegisterInfo *TRI = TM->getRegisterInfo();
Chris Lattner749c6f62008-01-07 07:27:27 +0000240 for (const unsigned *ImpDefs = I.getDesc().getImplicitDefs();
Chris Lattner69244302008-01-07 01:56:04 +0000241 *ImpDefs; ++ImpDefs)
Bill Wendlingb7a89922009-08-22 20:25:44 +0000242 errs() << " -> " << TRI->getName(*ImpDefs) << "\n";
Bill Wendling280f4562007-12-18 21:38:04 +0000243 }
Bill Wendling280f4562007-12-18 21:38:04 +0000244 });
245
Bill Wendlingd3361e92008-08-18 00:33:49 +0000246 if (I.getDesc().getImplicitDefs() || I.getDesc().getImplicitUses()) {
Bill Wendlingb7a89922009-08-22 20:25:44 +0000247 DEBUG(errs() << "Cannot hoist with implicit defines or uses\n");
Bill Wendlingd3361e92008-08-18 00:33:49 +0000248 return false;
249 }
250
Bill Wendlinge4fc1cc2008-05-12 19:38:32 +0000251 // The instruction is loop invariant if all of its operands are.
Bill Wendling0f940c92007-12-07 21:42:31 +0000252 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
253 const MachineOperand &MO = I.getOperand(i);
254
Dan Gohmand735b802008-10-03 15:45:36 +0000255 if (!MO.isReg())
Bill Wendlingfb018d02008-08-20 20:32:05 +0000256 continue;
257
Dan Gohmanc475c362009-01-15 22:01:38 +0000258 unsigned Reg = MO.getReg();
259 if (Reg == 0) continue;
260
261 // Don't hoist an instruction that uses or defines a physical register.
Dan Gohmana8fb3362009-09-25 23:58:45 +0000262 if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
Dan Gohmana8fb3362009-09-25 23:58:45 +0000263 if (MO.isUse()) {
264 // If the physreg has no defs anywhere, it's just an ambient register
Dan Gohman45094e32009-09-26 02:34:00 +0000265 // and we can freely move its uses. Alternatively, if it's allocatable,
266 // it could get allocated to something with a def during allocation.
Dan Gohmana8fb3362009-09-25 23:58:45 +0000267 if (!RegInfo->def_empty(Reg))
268 return false;
Dan Gohman45094e32009-09-26 02:34:00 +0000269 if (AllocatableSet.test(Reg))
270 return false;
Dan Gohmana8fb3362009-09-25 23:58:45 +0000271 // Check for a def among the register's aliases too.
Dan Gohman45094e32009-09-26 02:34:00 +0000272 for (const unsigned *Alias = TRI->getAliasSet(Reg); *Alias; ++Alias) {
273 unsigned AliasReg = *Alias;
274 if (!RegInfo->def_empty(AliasReg))
Dan Gohmana8fb3362009-09-25 23:58:45 +0000275 return false;
Dan Gohman45094e32009-09-26 02:34:00 +0000276 if (AllocatableSet.test(AliasReg))
277 return false;
278 }
Dan Gohmana8fb3362009-09-25 23:58:45 +0000279 // Otherwise it's safe to move.
280 continue;
281 } else if (!MO.isDead()) {
282 // A def that isn't dead. We can't move it.
283 return false;
284 }
285 }
Bill Wendlingfb018d02008-08-20 20:32:05 +0000286
287 if (!MO.isUse())
Bill Wendling0f940c92007-12-07 21:42:31 +0000288 continue;
289
Bill Wendlinge4fc1cc2008-05-12 19:38:32 +0000290 assert(RegInfo->getVRegDef(Reg) &&
291 "Machine instr not mapped for this vreg?!");
Bill Wendling0f940c92007-12-07 21:42:31 +0000292
293 // If the loop contains the definition of an operand, then the instruction
294 // isn't loop invariant.
Bill Wendling9258cd32008-01-02 19:32:43 +0000295 if (CurLoop->contains(RegInfo->getVRegDef(Reg)->getParent()))
Bill Wendling0f940c92007-12-07 21:42:31 +0000296 return false;
297 }
298
299 // If we got this far, the instruction is loop invariant!
300 return true;
301}
302
Evan Chengaf6949d2009-02-05 08:45:46 +0000303
304/// HasPHIUses - Return true if the specified register has any PHI use.
305static bool HasPHIUses(unsigned Reg, MachineRegisterInfo *RegInfo) {
Evan Cheng45e94d62009-02-04 09:19:56 +0000306 for (MachineRegisterInfo::use_iterator UI = RegInfo->use_begin(Reg),
307 UE = RegInfo->use_end(); UI != UE; ++UI) {
308 MachineInstr *UseMI = &*UI;
Evan Chengaf6949d2009-02-05 08:45:46 +0000309 if (UseMI->getOpcode() == TargetInstrInfo::PHI)
310 return true;
Evan Cheng45e94d62009-02-04 09:19:56 +0000311 }
Evan Chengaf6949d2009-02-05 08:45:46 +0000312 return false;
Evan Cheng45e94d62009-02-04 09:19:56 +0000313}
314
315/// IsProfitableToHoist - Return true if it is potentially profitable to hoist
316/// the given loop invariant.
317bool MachineLICM::IsProfitableToHoist(MachineInstr &MI) {
Evan Chengefc78392009-02-27 00:02:22 +0000318 if (MI.getOpcode() == TargetInstrInfo::IMPLICIT_DEF)
319 return false;
320
Evan Cheng45e94d62009-02-04 09:19:56 +0000321 // FIXME: For now, only hoist re-materilizable instructions. LICM will
322 // increase register pressure. We want to make sure it doesn't increase
323 // spilling.
Dan Gohmana70dca12009-10-09 23:27:56 +0000324 if (!TII->isTriviallyReMaterializable(&MI, AA))
Evan Cheng45e94d62009-02-04 09:19:56 +0000325 return false;
326
Evan Chengaf6949d2009-02-05 08:45:46 +0000327 // If result(s) of this instruction is used by PHIs, then don't hoist it.
328 // The presence of joins makes it difficult for current register allocator
329 // implementation to perform remat.
Evan Cheng45e94d62009-02-04 09:19:56 +0000330 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
331 const MachineOperand &MO = MI.getOperand(i);
332 if (!MO.isReg() || !MO.isDef())
333 continue;
Evan Chengaf6949d2009-02-05 08:45:46 +0000334 if (HasPHIUses(MO.getReg(), RegInfo))
335 return false;
Evan Cheng45e94d62009-02-04 09:19:56 +0000336 }
Evan Chengaf6949d2009-02-05 08:45:46 +0000337
338 return true;
339}
340
341static const MachineInstr *LookForDuplicate(const MachineInstr *MI,
Evan Chengefc78392009-02-27 00:02:22 +0000342 std::vector<const MachineInstr*> &PrevMIs,
343 MachineRegisterInfo *RegInfo) {
Evan Chengaf6949d2009-02-05 08:45:46 +0000344 unsigned NumOps = MI->getNumOperands();
345 for (unsigned i = 0, e = PrevMIs.size(); i != e; ++i) {
346 const MachineInstr *PrevMI = PrevMIs[i];
347 unsigned NumOps2 = PrevMI->getNumOperands();
348 if (NumOps != NumOps2)
349 continue;
350 bool IsSame = true;
351 for (unsigned j = 0; j != NumOps; ++j) {
352 const MachineOperand &MO = MI->getOperand(j);
Evan Chengefc78392009-02-27 00:02:22 +0000353 if (MO.isReg() && MO.isDef()) {
354 if (RegInfo->getRegClass(MO.getReg()) !=
355 RegInfo->getRegClass(PrevMI->getOperand(j).getReg())) {
356 IsSame = false;
357 break;
358 }
Evan Chengaf6949d2009-02-05 08:45:46 +0000359 continue;
Evan Chengefc78392009-02-27 00:02:22 +0000360 }
Evan Chengaf6949d2009-02-05 08:45:46 +0000361 if (!MO.isIdenticalTo(PrevMI->getOperand(j))) {
362 IsSame = false;
363 break;
364 }
365 }
366 if (IsSame)
367 return PrevMI;
368 }
369 return 0;
Evan Cheng45e94d62009-02-04 09:19:56 +0000370}
371
Bill Wendlinge4fc1cc2008-05-12 19:38:32 +0000372/// Hoist - When an instruction is found to use only loop invariant operands
373/// that are safe to hoist, this instruction is called to do the dirty work.
Bill Wendling0f940c92007-12-07 21:42:31 +0000374///
Dan Gohman589f1f52009-10-28 03:21:57 +0000375void MachineLICM::Hoist(MachineInstr *MI) {
376 // First check whether we should hoist this instruction.
377 if (!IsLoopInvariantInst(*MI) || !IsProfitableToHoist(*MI)) {
378 // If not, we may be able to unfold a load and hoist that.
379 // First test whether the instruction is loading from an amenable
380 // memory location.
381 if (!MI->getDesc().mayLoad()) return;
382 if (!MI->hasOneMemOperand()) return;
383 MachineMemOperand *MMO = *MI->memoperands_begin();
384 if (MMO->isVolatile()) return;
385 MachineFunction &MF = *MI->getParent()->getParent();
386 if (!MMO->getValue()) return;
387 if (const PseudoSourceValue *PSV =
388 dyn_cast<PseudoSourceValue>(MMO->getValue())) {
389 if (!PSV->isConstant(MF.getFrameInfo())) return;
390 } else {
391 if (!AA->pointsToConstantMemory(MMO->getValue())) return;
392 }
393 // Next determine the register class for a temporary register.
394 unsigned NewOpc =
395 TII->getOpcodeAfterMemoryUnfold(MI->getOpcode(),
396 /*UnfoldLoad=*/true,
397 /*UnfoldStore=*/false);
398 if (NewOpc == 0) return;
399 const TargetInstrDesc &TID = TII->get(NewOpc);
400 if (TID.getNumDefs() != 1) return;
401 const TargetRegisterClass *RC = TID.OpInfo[0].getRegClass(TRI);
402 // Ok, we're unfolding. Create a temporary register and do the unfold.
403 unsigned Reg = RegInfo->createVirtualRegister(RC);
404 SmallVector<MachineInstr *, 1> NewMIs;
405 bool Success =
406 TII->unfoldMemoryOperand(MF, MI, Reg,
407 /*UnfoldLoad=*/true, /*UnfoldStore=*/false,
408 NewMIs);
409 (void)Success;
410 assert(Success &&
411 "unfoldMemoryOperand failed when getOpcodeAfterMemoryUnfold "
412 "succeeded!");
413 assert(NewMIs.size() == 2 &&
414 "Unfolded a load into multiple instructions!");
415 MachineBasicBlock *MBB = MI->getParent();
416 MBB->insert(MI, NewMIs[0]);
417 MBB->insert(MI, NewMIs[1]);
418 MI->eraseFromParent();
419 // If unfolding produced a load that wasn't loop-invariant or profitable to
420 // hoist, re-fold it to undo the damage.
421 if (!IsLoopInvariantInst(*NewMIs[0]) || !IsProfitableToHoist(*NewMIs[0])) {
422 SmallVector<unsigned, 1> Ops;
423 for (unsigned i = 0, e = NewMIs[1]->getNumOperands(); i != e; ++i) {
424 MachineOperand &MO = NewMIs[1]->getOperand(i);
425 if (MO.isReg() && MO.getReg() == Reg) {
426 assert(MO.isUse() &&
427 "Register defined by unfolded load is redefined "
428 "instead of just used!");
429 Ops.push_back(i);
430 }
431 }
432 MI = TII->foldMemoryOperand(MF, NewMIs[1], Ops, NewMIs[0]);
433 assert(MI && "Re-fold failed!");
434 MBB->insert(NewMIs[1], MI);
435 NewMIs[0]->eraseFromParent();
436 NewMIs[1]->eraseFromParent();
437 return;
438 }
439 // Otherwise we successfully unfolded a load that we can hoist.
440 MI = NewMIs[0];
441 }
Bill Wendling0f940c92007-12-07 21:42:31 +0000442
Dan Gohmanc475c362009-01-15 22:01:38 +0000443 // Now move the instructions to the predecessor, inserting it before any
444 // terminator instructions.
445 DEBUG({
Dan Gohman589f1f52009-10-28 03:21:57 +0000446 errs() << "Hoisting " << *MI;
Dan Gohmanc475c362009-01-15 22:01:38 +0000447 if (CurPreheader->getBasicBlock())
Daniel Dunbarce63ffb2009-07-25 00:23:56 +0000448 errs() << " to MachineBasicBlock "
449 << CurPreheader->getBasicBlock()->getName();
Dan Gohman589f1f52009-10-28 03:21:57 +0000450 if (MI->getParent()->getBasicBlock())
Daniel Dunbarce63ffb2009-07-25 00:23:56 +0000451 errs() << " from MachineBasicBlock "
Dan Gohman589f1f52009-10-28 03:21:57 +0000452 << MI->getParent()->getBasicBlock()->getName();
Daniel Dunbarce63ffb2009-07-25 00:23:56 +0000453 errs() << "\n";
Dan Gohmanc475c362009-01-15 22:01:38 +0000454 });
Bill Wendling0f940c92007-12-07 21:42:31 +0000455
Evan Chengaf6949d2009-02-05 08:45:46 +0000456 // Look for opportunity to CSE the hoisted instruction.
457 std::pair<unsigned, unsigned> BBOpcPair =
Dan Gohman589f1f52009-10-28 03:21:57 +0000458 std::make_pair(CurPreheader->getNumber(), MI->getOpcode());
Evan Chengaf6949d2009-02-05 08:45:46 +0000459 DenseMap<std::pair<unsigned, unsigned>,
460 std::vector<const MachineInstr*> >::iterator CI = CSEMap.find(BBOpcPair);
461 bool DoneCSE = false;
462 if (CI != CSEMap.end()) {
Dan Gohman589f1f52009-10-28 03:21:57 +0000463 const MachineInstr *Dup = LookForDuplicate(MI, CI->second, RegInfo);
Evan Chengaf6949d2009-02-05 08:45:46 +0000464 if (Dup) {
Dan Gohman589f1f52009-10-28 03:21:57 +0000465 DEBUG(errs() << "CSEing " << *MI << " with " << *Dup);
466 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
467 const MachineOperand &MO = MI->getOperand(i);
Evan Chengaf6949d2009-02-05 08:45:46 +0000468 if (MO.isReg() && MO.isDef())
469 RegInfo->replaceRegWith(MO.getReg(), Dup->getOperand(i).getReg());
470 }
Dan Gohman589f1f52009-10-28 03:21:57 +0000471 MI->eraseFromParent();
Evan Chengaf6949d2009-02-05 08:45:46 +0000472 DoneCSE = true;
473 ++NumCSEed;
474 }
475 }
476
477 // Otherwise, splice the instruction to the preheader.
478 if (!DoneCSE) {
479 CurPreheader->splice(CurPreheader->getFirstTerminator(),
Dan Gohman589f1f52009-10-28 03:21:57 +0000480 MI->getParent(), MI);
Evan Chengaf6949d2009-02-05 08:45:46 +0000481 // Add to the CSE map.
482 if (CI != CSEMap.end())
Dan Gohman589f1f52009-10-28 03:21:57 +0000483 CI->second.push_back(MI);
Evan Chengaf6949d2009-02-05 08:45:46 +0000484 else {
485 std::vector<const MachineInstr*> CSEMIs;
Dan Gohman589f1f52009-10-28 03:21:57 +0000486 CSEMIs.push_back(MI);
Evan Chengaf6949d2009-02-05 08:45:46 +0000487 CSEMap.insert(std::make_pair(BBOpcPair, CSEMIs));
488 }
489 }
Bill Wendling0f940c92007-12-07 21:42:31 +0000490
Dan Gohmanc475c362009-01-15 22:01:38 +0000491 ++NumHoisted;
Bill Wendling0f940c92007-12-07 21:42:31 +0000492 Changed = true;
Bill Wendling0f940c92007-12-07 21:42:31 +0000493}