blob: 7b64047c39cf2d4002ffed985fe3b7ad1e371464 [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
Dan Gohman5c952302009-10-29 17:47:20 +0000108 /// ExtractHoistableLoad - Unfold a load from the given machineinstr if
109 /// the load itself could be hoisted. Return the unfolded and hoistable
110 /// load, or null if the load couldn't be unfolded or if it wouldn't
111 /// be hoistable.
112 MachineInstr *ExtractHoistableLoad(MachineInstr *MI);
113
Bill Wendling0f940c92007-12-07 21:42:31 +0000114 /// Hoist - When an instruction is found to only use loop invariant operands
115 /// that is safe to hoist, this instruction is called to do the dirty work.
116 ///
Dan Gohman589f1f52009-10-28 03:21:57 +0000117 void Hoist(MachineInstr *MI);
Bill Wendling0f940c92007-12-07 21:42:31 +0000118 };
Bill Wendling0f940c92007-12-07 21:42:31 +0000119} // end anonymous namespace
120
Dan Gohman844731a2008-05-13 00:00:25 +0000121char MachineLICM::ID = 0;
122static RegisterPass<MachineLICM>
Bill Wendling8870ce92008-07-07 05:42:27 +0000123X("machinelicm", "Machine Loop Invariant Code Motion");
Dan Gohman844731a2008-05-13 00:00:25 +0000124
Bill Wendling0f940c92007-12-07 21:42:31 +0000125FunctionPass *llvm::createMachineLICMPass() { return new MachineLICM(); }
126
Dan Gohmanc475c362009-01-15 22:01:38 +0000127/// LoopIsOuterMostWithPreheader - Test if the given loop is the outer-most
128/// loop that has a preheader.
129static bool LoopIsOuterMostWithPreheader(MachineLoop *CurLoop) {
130 for (MachineLoop *L = CurLoop->getParentLoop(); L; L = L->getParentLoop())
131 if (L->getLoopPreheader())
132 return false;
133 return true;
134}
135
Bill Wendling0f940c92007-12-07 21:42:31 +0000136/// Hoist expressions out of the specified loop. Note, alias info for inner loop
137/// is not preserved so it is not a good idea to run LICM multiple times on one
138/// loop.
139///
140bool MachineLICM::runOnMachineFunction(MachineFunction &MF) {
Bill Wendlingb7a89922009-08-22 20:25:44 +0000141 DEBUG(errs() << "******** Machine LICM ********\n");
Bill Wendlinga17ad592007-12-11 22:22:22 +0000142
Bill Wendling0f940c92007-12-07 21:42:31 +0000143 Changed = false;
Bill Wendlingacb04ec2008-08-31 02:30:23 +0000144 TM = &MF.getTarget();
Bill Wendling9258cd32008-01-02 19:32:43 +0000145 TII = TM->getInstrInfo();
Dan Gohmana8fb3362009-09-25 23:58:45 +0000146 TRI = TM->getRegisterInfo();
Bill Wendlingacb04ec2008-08-31 02:30:23 +0000147 RegInfo = &MF.getRegInfo();
Dan Gohman45094e32009-09-26 02:34:00 +0000148 AllocatableSet = TRI->getAllocatableSet(MF);
Bill Wendling0f940c92007-12-07 21:42:31 +0000149
150 // Get our Loop information...
151 LI = &getAnalysis<MachineLoopInfo>();
152 DT = &getAnalysis<MachineDominatorTree>();
Dan Gohmane33f44c2009-10-07 17:38:06 +0000153 AA = &getAnalysis<AliasAnalysis>();
Bill Wendling0f940c92007-12-07 21:42:31 +0000154
155 for (MachineLoopInfo::iterator
156 I = LI->begin(), E = LI->end(); I != E; ++I) {
Bill Wendlinga17ad592007-12-11 22:22:22 +0000157 CurLoop = *I;
Bill Wendling0f940c92007-12-07 21:42:31 +0000158
Dan Gohmanc475c362009-01-15 22:01:38 +0000159 // Only visit outer-most preheader-sporting loops.
160 if (!LoopIsOuterMostWithPreheader(CurLoop))
161 continue;
162
163 // Determine the block to which to hoist instructions. If we can't find a
164 // suitable loop preheader, we can't do any hoisting.
165 //
166 // FIXME: We are only hoisting if the basic block coming into this loop
167 // has only one successor. This isn't the case in general because we haven't
168 // broken critical edges or added preheaders.
169 CurPreheader = CurLoop->getLoopPreheader();
170 if (!CurPreheader)
171 continue;
172
173 HoistRegion(DT->getNode(CurLoop->getHeader()));
Bill Wendling0f940c92007-12-07 21:42:31 +0000174 }
175
176 return Changed;
177}
178
Bill Wendling0f940c92007-12-07 21:42:31 +0000179/// HoistRegion - Walk the specified region of the CFG (defined by all blocks
180/// dominated by the specified block, and that are in the current loop) in depth
181/// first order w.r.t the DominatorTree. This allows us to visit definitions
182/// before uses, allowing us to hoist a loop body in one pass without iteration.
183///
184void MachineLICM::HoistRegion(MachineDomTreeNode *N) {
185 assert(N != 0 && "Null dominator tree node?");
186 MachineBasicBlock *BB = N->getBlock();
187
188 // If this subregion is not in the top level loop at all, exit.
189 if (!CurLoop->contains(BB)) return;
190
Dan Gohmanc475c362009-01-15 22:01:38 +0000191 for (MachineBasicBlock::iterator
Evan Chengaf6949d2009-02-05 08:45:46 +0000192 MII = BB->begin(), E = BB->end(); MII != E; ) {
193 MachineBasicBlock::iterator NextMII = MII; ++NextMII;
194 MachineInstr &MI = *MII;
Bill Wendling0f940c92007-12-07 21:42:31 +0000195
Dan Gohman589f1f52009-10-28 03:21:57 +0000196 Hoist(&MI);
Evan Chengaf6949d2009-02-05 08:45:46 +0000197
198 MII = NextMII;
Dan Gohmanc475c362009-01-15 22:01:38 +0000199 }
Bill Wendling0f940c92007-12-07 21:42:31 +0000200
201 const std::vector<MachineDomTreeNode*> &Children = N->getChildren();
202
203 for (unsigned I = 0, E = Children.size(); I != E; ++I)
204 HoistRegion(Children[I]);
205}
206
Bill Wendling041b3f82007-12-08 23:58:46 +0000207/// IsLoopInvariantInst - Returns true if the instruction is loop
Bill Wendling0f940c92007-12-07 21:42:31 +0000208/// invariant. I.e., all virtual register operands are defined outside of the
Bill Wendling60ff1a32007-12-20 01:08:10 +0000209/// loop, physical registers aren't accessed explicitly, and there are no side
210/// effects that aren't captured by the operands or other flags.
Bill Wendling0f940c92007-12-07 21:42:31 +0000211///
Bill Wendling041b3f82007-12-08 23:58:46 +0000212bool MachineLICM::IsLoopInvariantInst(MachineInstr &I) {
Chris Lattnera22edc82008-01-10 23:08:24 +0000213 const TargetInstrDesc &TID = I.getDesc();
214
215 // Ignore stuff that we obviously can't hoist.
Dan Gohman237dee12008-12-23 17:28:50 +0000216 if (TID.mayStore() || TID.isCall() || TID.isTerminator() ||
Chris Lattnera22edc82008-01-10 23:08:24 +0000217 TID.hasUnmodeledSideEffects())
218 return false;
Evan Cheng9b61f332009-02-04 07:17:49 +0000219
Chris Lattnera22edc82008-01-10 23:08:24 +0000220 if (TID.mayLoad()) {
Bill Wendlinge4fc1cc2008-05-12 19:38:32 +0000221 // Okay, this instruction does a load. As a refinement, we allow the target
222 // to decide whether the loaded value is actually a constant. If so, we can
223 // actually use it as a load.
Dan Gohmane33f44c2009-10-07 17:38:06 +0000224 if (!I.isInvariantLoad(AA))
Chris Lattnera22edc82008-01-10 23:08:24 +0000225 // FIXME: we should be able to sink loads with no other side effects if
226 // there is nothing that can change memory from here until the end of
Bill Wendlinge4fc1cc2008-05-12 19:38:32 +0000227 // block. This is a trivial form of alias analysis.
Chris Lattnera22edc82008-01-10 23:08:24 +0000228 return false;
Chris Lattnera22edc82008-01-10 23:08:24 +0000229 }
Bill Wendling074223a2008-03-10 08:13:01 +0000230
Bill Wendling280f4562007-12-18 21:38:04 +0000231 DEBUG({
Bill Wendlingb7a89922009-08-22 20:25:44 +0000232 errs() << "--- Checking if we can hoist " << I;
Chris Lattner749c6f62008-01-07 07:27:27 +0000233 if (I.getDesc().getImplicitUses()) {
Bill Wendlingb7a89922009-08-22 20:25:44 +0000234 errs() << " * Instruction has implicit uses:\n";
Bill Wendling280f4562007-12-18 21:38:04 +0000235
Dan Gohman6f0d0242008-02-10 18:45:23 +0000236 const TargetRegisterInfo *TRI = TM->getRegisterInfo();
Chris Lattner749c6f62008-01-07 07:27:27 +0000237 for (const unsigned *ImpUses = I.getDesc().getImplicitUses();
Chris Lattner69244302008-01-07 01:56:04 +0000238 *ImpUses; ++ImpUses)
Bill Wendlingb7a89922009-08-22 20:25:44 +0000239 errs() << " -> " << TRI->getName(*ImpUses) << "\n";
Bill Wendling280f4562007-12-18 21:38:04 +0000240 }
241
Chris Lattner749c6f62008-01-07 07:27:27 +0000242 if (I.getDesc().getImplicitDefs()) {
Bill Wendlingb7a89922009-08-22 20:25:44 +0000243 errs() << " * Instruction has implicit defines:\n";
Bill Wendling280f4562007-12-18 21:38:04 +0000244
Dan Gohman6f0d0242008-02-10 18:45:23 +0000245 const TargetRegisterInfo *TRI = TM->getRegisterInfo();
Chris Lattner749c6f62008-01-07 07:27:27 +0000246 for (const unsigned *ImpDefs = I.getDesc().getImplicitDefs();
Chris Lattner69244302008-01-07 01:56:04 +0000247 *ImpDefs; ++ImpDefs)
Bill Wendlingb7a89922009-08-22 20:25:44 +0000248 errs() << " -> " << TRI->getName(*ImpDefs) << "\n";
Bill Wendling280f4562007-12-18 21:38:04 +0000249 }
Bill Wendling280f4562007-12-18 21:38:04 +0000250 });
251
Bill Wendlingd3361e92008-08-18 00:33:49 +0000252 if (I.getDesc().getImplicitDefs() || I.getDesc().getImplicitUses()) {
Bill Wendlingb7a89922009-08-22 20:25:44 +0000253 DEBUG(errs() << "Cannot hoist with implicit defines or uses\n");
Bill Wendlingd3361e92008-08-18 00:33:49 +0000254 return false;
255 }
256
Bill Wendlinge4fc1cc2008-05-12 19:38:32 +0000257 // The instruction is loop invariant if all of its operands are.
Bill Wendling0f940c92007-12-07 21:42:31 +0000258 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
259 const MachineOperand &MO = I.getOperand(i);
260
Dan Gohmand735b802008-10-03 15:45:36 +0000261 if (!MO.isReg())
Bill Wendlingfb018d02008-08-20 20:32:05 +0000262 continue;
263
Dan Gohmanc475c362009-01-15 22:01:38 +0000264 unsigned Reg = MO.getReg();
265 if (Reg == 0) continue;
266
267 // Don't hoist an instruction that uses or defines a physical register.
Dan Gohmana8fb3362009-09-25 23:58:45 +0000268 if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
Dan Gohmana8fb3362009-09-25 23:58:45 +0000269 if (MO.isUse()) {
270 // If the physreg has no defs anywhere, it's just an ambient register
Dan Gohman45094e32009-09-26 02:34:00 +0000271 // and we can freely move its uses. Alternatively, if it's allocatable,
272 // it could get allocated to something with a def during allocation.
Dan Gohmana8fb3362009-09-25 23:58:45 +0000273 if (!RegInfo->def_empty(Reg))
274 return false;
Dan Gohman45094e32009-09-26 02:34:00 +0000275 if (AllocatableSet.test(Reg))
276 return false;
Dan Gohmana8fb3362009-09-25 23:58:45 +0000277 // Check for a def among the register's aliases too.
Dan Gohman45094e32009-09-26 02:34:00 +0000278 for (const unsigned *Alias = TRI->getAliasSet(Reg); *Alias; ++Alias) {
279 unsigned AliasReg = *Alias;
280 if (!RegInfo->def_empty(AliasReg))
Dan Gohmana8fb3362009-09-25 23:58:45 +0000281 return false;
Dan Gohman45094e32009-09-26 02:34:00 +0000282 if (AllocatableSet.test(AliasReg))
283 return false;
284 }
Dan Gohmana8fb3362009-09-25 23:58:45 +0000285 // Otherwise it's safe to move.
286 continue;
287 } else if (!MO.isDead()) {
288 // A def that isn't dead. We can't move it.
289 return false;
290 }
291 }
Bill Wendlingfb018d02008-08-20 20:32:05 +0000292
293 if (!MO.isUse())
Bill Wendling0f940c92007-12-07 21:42:31 +0000294 continue;
295
Bill Wendlinge4fc1cc2008-05-12 19:38:32 +0000296 assert(RegInfo->getVRegDef(Reg) &&
297 "Machine instr not mapped for this vreg?!");
Bill Wendling0f940c92007-12-07 21:42:31 +0000298
299 // If the loop contains the definition of an operand, then the instruction
300 // isn't loop invariant.
Bill Wendling9258cd32008-01-02 19:32:43 +0000301 if (CurLoop->contains(RegInfo->getVRegDef(Reg)->getParent()))
Bill Wendling0f940c92007-12-07 21:42:31 +0000302 return false;
303 }
304
305 // If we got this far, the instruction is loop invariant!
306 return true;
307}
308
Evan Chengaf6949d2009-02-05 08:45:46 +0000309
310/// HasPHIUses - Return true if the specified register has any PHI use.
311static bool HasPHIUses(unsigned Reg, MachineRegisterInfo *RegInfo) {
Evan Cheng45e94d62009-02-04 09:19:56 +0000312 for (MachineRegisterInfo::use_iterator UI = RegInfo->use_begin(Reg),
313 UE = RegInfo->use_end(); UI != UE; ++UI) {
314 MachineInstr *UseMI = &*UI;
Evan Chengaf6949d2009-02-05 08:45:46 +0000315 if (UseMI->getOpcode() == TargetInstrInfo::PHI)
316 return true;
Evan Cheng45e94d62009-02-04 09:19:56 +0000317 }
Evan Chengaf6949d2009-02-05 08:45:46 +0000318 return false;
Evan Cheng45e94d62009-02-04 09:19:56 +0000319}
320
321/// IsProfitableToHoist - Return true if it is potentially profitable to hoist
322/// the given loop invariant.
323bool MachineLICM::IsProfitableToHoist(MachineInstr &MI) {
Evan Chengefc78392009-02-27 00:02:22 +0000324 if (MI.getOpcode() == TargetInstrInfo::IMPLICIT_DEF)
325 return false;
326
Evan Cheng45e94d62009-02-04 09:19:56 +0000327 // FIXME: For now, only hoist re-materilizable instructions. LICM will
328 // increase register pressure. We want to make sure it doesn't increase
329 // spilling.
Dan Gohmana70dca12009-10-09 23:27:56 +0000330 if (!TII->isTriviallyReMaterializable(&MI, AA))
Evan Cheng45e94d62009-02-04 09:19:56 +0000331 return false;
332
Evan Chengaf6949d2009-02-05 08:45:46 +0000333 // If result(s) of this instruction is used by PHIs, then don't hoist it.
334 // The presence of joins makes it difficult for current register allocator
335 // implementation to perform remat.
Evan Cheng45e94d62009-02-04 09:19:56 +0000336 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
337 const MachineOperand &MO = MI.getOperand(i);
338 if (!MO.isReg() || !MO.isDef())
339 continue;
Evan Chengaf6949d2009-02-05 08:45:46 +0000340 if (HasPHIUses(MO.getReg(), RegInfo))
341 return false;
Evan Cheng45e94d62009-02-04 09:19:56 +0000342 }
Evan Chengaf6949d2009-02-05 08:45:46 +0000343
344 return true;
345}
346
347static const MachineInstr *LookForDuplicate(const MachineInstr *MI,
Evan Chengefc78392009-02-27 00:02:22 +0000348 std::vector<const MachineInstr*> &PrevMIs,
349 MachineRegisterInfo *RegInfo) {
Evan Chengaf6949d2009-02-05 08:45:46 +0000350 unsigned NumOps = MI->getNumOperands();
351 for (unsigned i = 0, e = PrevMIs.size(); i != e; ++i) {
352 const MachineInstr *PrevMI = PrevMIs[i];
353 unsigned NumOps2 = PrevMI->getNumOperands();
354 if (NumOps != NumOps2)
355 continue;
356 bool IsSame = true;
357 for (unsigned j = 0; j != NumOps; ++j) {
358 const MachineOperand &MO = MI->getOperand(j);
Evan Chengefc78392009-02-27 00:02:22 +0000359 if (MO.isReg() && MO.isDef()) {
360 if (RegInfo->getRegClass(MO.getReg()) !=
361 RegInfo->getRegClass(PrevMI->getOperand(j).getReg())) {
362 IsSame = false;
363 break;
364 }
Evan Chengaf6949d2009-02-05 08:45:46 +0000365 continue;
Evan Chengefc78392009-02-27 00:02:22 +0000366 }
Evan Chengaf6949d2009-02-05 08:45:46 +0000367 if (!MO.isIdenticalTo(PrevMI->getOperand(j))) {
368 IsSame = false;
369 break;
370 }
371 }
372 if (IsSame)
373 return PrevMI;
374 }
375 return 0;
Evan Cheng45e94d62009-02-04 09:19:56 +0000376}
377
Dan Gohman5c952302009-10-29 17:47:20 +0000378MachineInstr *MachineLICM::ExtractHoistableLoad(MachineInstr *MI) {
379 // If not, we may be able to unfold a load and hoist that.
380 // First test whether the instruction is loading from an amenable
381 // memory location.
382 if (!MI->getDesc().mayLoad()) return 0;
383 if (!MI->hasOneMemOperand()) return 0;
384 MachineMemOperand *MMO = *MI->memoperands_begin();
385 if (MMO->isVolatile()) return 0;
386 MachineFunction &MF = *MI->getParent()->getParent();
387 if (!MMO->getValue()) return 0;
388 if (const PseudoSourceValue *PSV =
389 dyn_cast<PseudoSourceValue>(MMO->getValue())) {
390 if (!PSV->isConstant(MF.getFrameInfo())) return 0;
391 } else {
392 if (!AA->pointsToConstantMemory(MMO->getValue())) return 0;
393 }
394 // Next determine the register class for a temporary register.
Dan Gohman0115e162009-10-30 22:18:41 +0000395 unsigned LoadRegIndex;
Dan Gohman5c952302009-10-29 17:47:20 +0000396 unsigned NewOpc =
397 TII->getOpcodeAfterMemoryUnfold(MI->getOpcode(),
398 /*UnfoldLoad=*/true,
Dan Gohman0115e162009-10-30 22:18:41 +0000399 /*UnfoldStore=*/false,
400 &LoadRegIndex);
Dan Gohman5c952302009-10-29 17:47:20 +0000401 if (NewOpc == 0) return 0;
402 const TargetInstrDesc &TID = TII->get(NewOpc);
403 if (TID.getNumDefs() != 1) return 0;
Dan Gohman0115e162009-10-30 22:18:41 +0000404 const TargetRegisterClass *RC = TID.OpInfo[LoadRegIndex].getRegClass(TRI);
Dan Gohman5c952302009-10-29 17:47:20 +0000405 // Ok, we're unfolding. Create a temporary register and do the unfold.
406 unsigned Reg = RegInfo->createVirtualRegister(RC);
407 SmallVector<MachineInstr *, 2> NewMIs;
408 bool Success =
409 TII->unfoldMemoryOperand(MF, MI, Reg,
410 /*UnfoldLoad=*/true, /*UnfoldStore=*/false,
411 NewMIs);
412 (void)Success;
413 assert(Success &&
414 "unfoldMemoryOperand failed when getOpcodeAfterMemoryUnfold "
415 "succeeded!");
416 assert(NewMIs.size() == 2 &&
417 "Unfolded a load into multiple instructions!");
418 MachineBasicBlock *MBB = MI->getParent();
419 MBB->insert(MI, NewMIs[0]);
420 MBB->insert(MI, NewMIs[1]);
421 // If unfolding produced a load that wasn't loop-invariant or profitable to
422 // hoist, discard the new instructions and bail.
423 if (!IsLoopInvariantInst(*NewMIs[0]) || !IsProfitableToHoist(*NewMIs[0])) {
424 NewMIs[0]->eraseFromParent();
425 NewMIs[1]->eraseFromParent();
426 return 0;
427 }
428 // Otherwise we successfully unfolded a load that we can hoist.
429 MI->eraseFromParent();
430 return NewMIs[0];
431}
432
Bill Wendlinge4fc1cc2008-05-12 19:38:32 +0000433/// Hoist - When an instruction is found to use only loop invariant operands
434/// that are safe to hoist, this instruction is called to do the dirty work.
Bill Wendling0f940c92007-12-07 21:42:31 +0000435///
Dan Gohman589f1f52009-10-28 03:21:57 +0000436void MachineLICM::Hoist(MachineInstr *MI) {
437 // First check whether we should hoist this instruction.
438 if (!IsLoopInvariantInst(*MI) || !IsProfitableToHoist(*MI)) {
Dan Gohman5c952302009-10-29 17:47:20 +0000439 // If not, try unfolding a hoistable load.
440 MI = ExtractHoistableLoad(MI);
441 if (!MI) return;
Dan Gohman589f1f52009-10-28 03:21:57 +0000442 }
Bill Wendling0f940c92007-12-07 21:42:31 +0000443
Dan Gohmanc475c362009-01-15 22:01:38 +0000444 // Now move the instructions to the predecessor, inserting it before any
445 // terminator instructions.
446 DEBUG({
Dan Gohman589f1f52009-10-28 03:21:57 +0000447 errs() << "Hoisting " << *MI;
Dan Gohmanc475c362009-01-15 22:01:38 +0000448 if (CurPreheader->getBasicBlock())
Daniel Dunbarce63ffb2009-07-25 00:23:56 +0000449 errs() << " to MachineBasicBlock "
450 << CurPreheader->getBasicBlock()->getName();
Dan Gohman589f1f52009-10-28 03:21:57 +0000451 if (MI->getParent()->getBasicBlock())
Daniel Dunbarce63ffb2009-07-25 00:23:56 +0000452 errs() << " from MachineBasicBlock "
Dan Gohman589f1f52009-10-28 03:21:57 +0000453 << MI->getParent()->getBasicBlock()->getName();
Daniel Dunbarce63ffb2009-07-25 00:23:56 +0000454 errs() << "\n";
Dan Gohmanc475c362009-01-15 22:01:38 +0000455 });
Bill Wendling0f940c92007-12-07 21:42:31 +0000456
Evan Chengaf6949d2009-02-05 08:45:46 +0000457 // Look for opportunity to CSE the hoisted instruction.
458 std::pair<unsigned, unsigned> BBOpcPair =
Dan Gohman589f1f52009-10-28 03:21:57 +0000459 std::make_pair(CurPreheader->getNumber(), MI->getOpcode());
Evan Chengaf6949d2009-02-05 08:45:46 +0000460 DenseMap<std::pair<unsigned, unsigned>,
461 std::vector<const MachineInstr*> >::iterator CI = CSEMap.find(BBOpcPair);
462 bool DoneCSE = false;
463 if (CI != CSEMap.end()) {
Dan Gohman589f1f52009-10-28 03:21:57 +0000464 const MachineInstr *Dup = LookForDuplicate(MI, CI->second, RegInfo);
Evan Chengaf6949d2009-02-05 08:45:46 +0000465 if (Dup) {
Dan Gohman589f1f52009-10-28 03:21:57 +0000466 DEBUG(errs() << "CSEing " << *MI << " with " << *Dup);
467 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
468 const MachineOperand &MO = MI->getOperand(i);
Evan Chengaf6949d2009-02-05 08:45:46 +0000469 if (MO.isReg() && MO.isDef())
470 RegInfo->replaceRegWith(MO.getReg(), Dup->getOperand(i).getReg());
471 }
Dan Gohman589f1f52009-10-28 03:21:57 +0000472 MI->eraseFromParent();
Evan Chengaf6949d2009-02-05 08:45:46 +0000473 DoneCSE = true;
474 ++NumCSEed;
475 }
476 }
477
478 // Otherwise, splice the instruction to the preheader.
479 if (!DoneCSE) {
480 CurPreheader->splice(CurPreheader->getFirstTerminator(),
Dan Gohman589f1f52009-10-28 03:21:57 +0000481 MI->getParent(), MI);
Evan Chengaf6949d2009-02-05 08:45:46 +0000482 // Add to the CSE map.
483 if (CI != CSEMap.end())
Dan Gohman589f1f52009-10-28 03:21:57 +0000484 CI->second.push_back(MI);
Evan Chengaf6949d2009-02-05 08:45:46 +0000485 else {
486 std::vector<const MachineInstr*> CSEMIs;
Dan Gohman589f1f52009-10-28 03:21:57 +0000487 CSEMIs.push_back(MI);
Evan Chengaf6949d2009-02-05 08:45:46 +0000488 CSEMap.insert(std::make_pair(BBOpcPair, CSEMIs));
489 }
490 }
Bill Wendling0f940c92007-12-07 21:42:31 +0000491
Dan Gohmanc475c362009-01-15 22:01:38 +0000492 ++NumHoisted;
Bill Wendling0f940c92007-12-07 21:42:31 +0000493 Changed = true;
Bill Wendling0f940c92007-12-07 21:42:31 +0000494}